package receiver.screens;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.graphics.drawable.shapes.RoundRectShape;
import android.view.View;

public class VisualizationView extends View {
	public static final int tickRatio = 10;
	private List<VisualizationData> data;
	private long prevTime;
	private int current;
	private long first;
	private int tick;
	private int continuousTick;
	
	public VisualizationView(Context context, List<VisualizationData> data) {
		super(context);
		//this.drawables = new ArrayList<ShapeDrawable>();
		this.data = data;
		//this.setBackgroundColor(Color.BLUE);
		prevTime = 0;
		current = 0;
		tick = 1;
		continuousTick = 1;
	}
	
	protected void onDraw(Canvas canvas) {
		if(current >= data.size())
			return;
		
		if(prevTime == 0) {
			first = System.currentTimeMillis();
			prevTime = first;
		}
		
		long newTime = System.currentTimeMillis();
		
		int w = this.getWidth();
		int h = this.getHeight();
		
		float duration = (float) data.get(current).duration;
		
		if(tick > duration) {
			current++;
			if(current >= data.size())
				return;
			prevTime = newTime;
			tick = (int) (data.get(current).start - continuousTick);
		}
		
		if(newTime - prevTime > tickRatio) {
			tick++;
			continuousTick++;
			prevTime = newTime;
			invalidate();
		}
		
		if(tick > 0) {
			float origin = (float) (Math.min(w, h) / 2.0);
			float scale = (float) (origin / duration);
			float rad = Math.max(scale * tick, data.get(current).loudness);
			
			Paint p = new Paint();
			p.setStyle(Paint.Style.STROKE);
			if(data.get(current).color != Color.BLACK)
				p.setColor(data.get(current).color);
			else
				p.setColor(Color.WHITE);
			
			
			p.setStrokeWidth(data.get(current).loudness);
			
			canvas.drawCircle(origin, origin, rad, p);
		
		}
		invalidate();
		
//		for(int i = 0; i + 2 < data.length; i += 3) {
//			rad -= data[i + 1] * scale / 2;
//			p.setStrokeWidth(data[i + 1] * scale / 2);
//			
//			if(data[i] < 33)
//				p.setColor(Color.GREEN);
//			else if(data[i] < 66)
//				p.setColor(Color.YELLOW);
//			else
//				p.setColor(Color.RED);
//			
//			canvas.drawCircle(origin, origin, rad, p);
//			
//			rad -= data[i+2] * scale;
//		}
		
		
		//canvas.setBitmap(bmap);
//		for(ShapeDrawable mDrawable : drawables)
//			mDrawable.draw(canvas);
	}
	
	public void resetAnimation() {
		current = 0;
		prevTime = 0;
		tick = 1;
		continuousTick = 1;
		invalidate();
	}
	
}
